<template>
  <!--    弹出框-->
  <el-dialog
    :title="titleText"
    :visible="showDialog"
    width="50%"
    @close="onClose"
  >
    <el-form ref="addForm" :hide-required-asterisk="true" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          :loading="isLoading"
          loading-text="正在加载中..."
          placeholder="请选择部门负责人"
          value=""
          @focus="loadEmployeesList"
        >
          <el-option v-for="item in employeesList" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
      <el-form-item>
        <span class="dialog-footer">
          <el-button @click="onClose">取 消</el-button>
          <el-button type="primary" :loading="btnIsLoading" @click="submitFrom">确 定</el-button>
        </span>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getEmployeesSimpleList } from '@/api/employees'
import { addDept, getDepartments, updateDept } from '@/api/departments'

export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    row: {
      type: Object,
      required: true
    }
  },
  data() {
    // 检测部门是否存在
    const whetherTheInspectionDepartmentIsDuplicated = async(rule, val, callback) => {
      let isRepeat
      if (this.form.id) {
        // 编辑
        const { depts } = await getDepartments() // 获取所有列表数据
        const siblings = depts.filter(item => item.pid === this.row.pid) // 查找所有的兄弟部门
        isRepeat = val === this.row.name && siblings.some(item => item.name !== val)
      } else {
        // 添加
        if (!this.row.children) return callback()
        isRepeat = this.row.children.some(item => item.name === val)
      }
      return isRepeat ? callback(new Error('部门已存在')) : callback()
    }
    // 检验部门编码是否重复
    const checkWhetherTheDepartmentCodeIsDuplicated = async(rule, val, callback) => {
      let isRepeat

      const { depts } = await getDepartments()
      if (this.form.id) {
        const siblings = depts.filter(item => item.code === this.row.code) // 查找所有的兄弟部门
        isRepeat = val === this.row.code && siblings.some(item => item.code !== val)
      } else {
        isRepeat = depts.some(item => item.code === val)
      }
      return isRepeat ? callback(new Error('部门编码已存在')) : callback()
    }
    return {
      form: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人名称
        name: '' // 部门名称
      },
      employeesList: [], // 员工列表
      isLoading: false,
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: whetherTheInspectionDepartmentIsDuplicated, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkWhetherTheDepartmentCodeIsDuplicated, trigger: 'blur' }

        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }
        ]
      },
      btnIsLoading: false// btn loading效果控制
    }
  },
  computed: {
    titleText() {
      return this.form.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    // this.loadEmployeesList()
  },
  methods: {
    // 触发删除事件
    onClose() {
      // 调用父组件的sync解析出来的方法
      this.$emit('update:show-dialog', false)
      this.$refs.addForm.resetFields()
      setTimeout(() => {
        this.form = {
          code: '',
          introduce: '',
          manager: '',
          name: ''
        }
      }, 200)
    },
    // 加载员工列表
    async loadEmployeesList() {
      this.isLoading = true
      this.employeesList = await getEmployeesSimpleList()
      this.isLoading = false
    },
    // 提交表单数据添加
    submitFrom() {
      this.btnIsLoading = true
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          if (this.form.id) {
            // 编辑
            await updateDept(this.form)
            this.$message.success('更新成功')
          } else {
            // 添加
            this.form.pid = this.row.id || ''
            await addDept(this.form)
            this.$message.success('添加成功')
          }
          this.btnIsLoading = false
          this.$emit('refreshData')
          this.onClose() // 关闭对话框
        } else {
          this.btnIsLoading = false
          return false
        }
      })
    },
    // 父组件调用方法给form表单赋值
    setForm() {
      this.form = JSON.parse(JSON.stringify(this.row))
    }
  }
}
</script>

<style scoped lang='less'>

</style>
